<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
          <div style="display: inline-block"></div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" style="text-align: right">
          <el-button  class="filter-button" v-waves icon="el-icon-back" @click="$router.back()">返回</el-button>
          <el-popover  class="filter-button" v-waves v-permission="['security:sysPermission:add']" width="300" placement="left">
            <p>请选择创建类型</p>
            <div style="text-align: center">
              <el-button  type="primary"  @click="handleCreateSysPermission('menu')">菜单</el-button>
              <el-button  type="success"  @click="handleCreateSysPermission('button')">按钮</el-button>
            </div>
            <el-button  slot="reference"  type="primary" icon="el-icon-edit">
              添加权限
            </el-button>
          </el-popover>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <tree-table-list ref="table" url="/security/sysPermission" :query="listQuery" :columns="columns" :format="format" :sort-change="handelChangeSortBy" :expandAll="false">
        <template slot="type" slot-scope="scope">
          <el-tag :type="scope.row.type | typeStyleFilter">{{ scope.row.type | typeFilter }}</el-tag>
        </template>
        <template slot="actions" slot-scope="scope">
          <el-popover v-if="scope.row.type == 'menu'" v-permission="['security:sysPermission:add']" width="160">
            <p>请选择创建类型</p>
            <div style="text-align: right; margin: 0">
              <el-button  type="primary"  @click="handleCreateSysPermission('menu', scope.row.id)">菜单</el-button>
              <el-button  type="success"  @click="handleCreateSysPermission('button', scope.row.id)">按钮</el-button>
            </div>
            <el-button  slot="reference" type="success"style="margin-right: 10px">添加</el-button>
          </el-popover>
          <el-button  v-waves v-permission="['security:sysPermission:edit']" type="primary" @click="handleEditSysPermission(scope.$index, scope.row)">编辑</el-button>
          <el-button  v-waves v-permission="['security:sysPermission:delete']" type="danger" @click="handleDeleteSysPermission(scope.$index, scope.row)">删除</el-button>
        </template>
      </tree-table-list>
      <el-dialog :title="dialogTextMap[dialogStatus]" :visible.sync="createDialogVisible" :width="$store.state.app.device === 'mobile' ? '100%' : '60%'">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" label-suffix=": " :inline="true">
          <el-form-item label="权限名称" prop="authorityName">
            <el-input  class="form-item" v-model="temp.authorityName" />
          </el-form-item>
          <el-form-item v-if="temp.type === 'button'" label="按钮权限值" prop="authority">
            <el-input  class="form-item" v-model="temp.authority" placeholder="如: user:edit"/>
          </el-form-item>
          <el-form-item label="API" prop="authorityPath">
            <el-input  class="form-item" v-model="temp.authorityPath" placeholder="如:/list , /file/** , /detail/*"/>
          </el-form-item>
          <el-form-item label="请求方式" prop="authorityMethod">
            <el-select  class="form-item" v-model="temp.authorityMethod" clearable placeholder="请选择">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
              <el-option label="PUT" value="PUT" />
              <el-option label="PATCH" value="PATCH" />
              <el-option label="DELETE" value="DELETE" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="temp.type === 'menu'" label="路由名称" prop="routerName">
            <el-input  class="form-item" v-model="temp.routerName" />
          </el-form-item>
          <el-form-item v-if="temp.type === 'menu'" label="路由URL" prop="routerPath">
            <el-input  class="form-item" v-model="temp.routerPath" />
          </el-form-item>
          <el-form-item v-if="temp.type === 'menu'" label="路由重定向" prop="routerRedirect">
            <el-input  class="form-item" v-model="temp.routerRedirect" />
          </el-form-item>
          <el-form-item v-if="temp.type === 'menu'" label="Vue资源" prop="routerComponent">
            <el-input  class="form-item" v-model="temp.routerComponent" placeholder="如:/views/dashboard/index" />
          </el-form-item>
          <el-form-item v-if="temp.type === 'menu'" label="菜单图标" prop="routerIcon">
            <el-input  class="form-item" v-model="temp.routerIcon" />
          </el-form-item>
          <el-form-item v-if="temp.type === 'menu'" label="路由缓存" prop="routerNoCache">
            <el-checkbox  class="form-item" v-model="temp.routerNoCache" />
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number  class="form-item" v-model="temp.sortBy" :min="0" label=""></el-input-number>
          </el-form-item>
          <el-form-item v-if="temp.type === 'menu'" label="是否隐藏" prop="hidden">
            <el-checkbox  class="form-item" v-model="temp.hidden">只在菜单中生效</el-checkbox>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button  v-waves @click="createDialogVisible = false">取消</el-button>
          <el-button  v-waves type="primary" v-permission="['security:sysPermission:add' || 'security:sysPermission:edit ']" @click="dialogStatus==='create'?handleAddSysPermission():handleUpdateSysPermission()">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import waves from '@/directive/waves' // waves directive
import { create as createSysPermission,
  update as updateSysPermission,
  deleteById as deleteSysPermission,
  changeSort as changeSysPermissionSort,} from '@/api/security/sysPermission'
import { mapGetters } from 'vuex'
import TreeTableList from '@/components/TreeTableList'
export default {
  name: 'SysPermission',
  components: { TreeTableList },
  directives: { permission, waves },
  filters: {
    typeFilter(type) {
      const map = {
        'menu': '菜单',
        'button': '按钮'
      }
      return map[type]
    },
    typeStyleFilter(type) {
      const map = {
        'menu': 'primary',
        'button': 'success'
      }
      return map[type]
    }
  },
  data() {
    return {
      list: null,
      columns: [
        { key: 'authorityName', label: '资源名称', minWidth: 320, fixed: 'left', align: 'left' },
        { key: 'authority', label: '权限值', width: 160, align: 'left' },
        { key: 'authorityPath', label: 'API', width: 320, align: 'left' },
        { key: 'routerPath', label: '路由路径', width: 200, align: 'left' },
        { key: 'routerRedirect', label: '路由跳转', width: 200, align: 'left' },
        { key: 'routerComponent', label: '路由页面', width: 200, align: 'left' },
        { key: 'sortBy', label: '排序', type: 'sort', width: 160 },
        { key: 'type', label: '路由类型', width: 100 },
        { key: 'hidden', label: '是否隐藏', width: 100 },
        { key: 'actions', label: '操作', width: 220, fixed: 'right', align: 'right' }
      ],
      format: {
        hidden:(data, index) => {return data.hidden ? '隐藏' : '显示'}
      },
      listQuery: {},
      temp: {parentId: undefined,authority: undefined,authorityName: undefined,authorityPath: undefined,authorityMethod: undefined,routerPath: undefined,routerName: undefined,routerRedirect: undefined,routerComponent: undefined,routerTitle: undefined,routerIcon: undefined,routerNoCache: undefined,sortBy: undefined,type: undefined,hidden: undefined},
      dialogTextMap: {update: '编辑',create: '新建', detail: '详情'},
      rules: {},
      dialogStatus: '',
      createDialogVisible: false,
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    const allOptions = JSON.parse(localStorage.getItem('allOptions'))
  },
  mounted() {
    this.fetchListData()
  },
  methods: {
    fetchListData() {
      this.$refs.table.fetchData(1)
    },
    reloadListData() {
      this.$refs.table.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        authority: '', // 权限标识
        authorityName: '', // 资源名称
        authorityPath: '', // 请求url路径
        authorityMethod: '', // 请求方式 POST/GET/PUT
        routerName: '', // 路由名称
        routerPath: '', // 路由路径
        routerRedirect: '', // 路由跳转
        routerComponent: '', // Vue资源路径
        routerTitle: '', // 路由标题
        routerIcon: '', // Icon资源名
        routerNoCache: false, // 是否缓存
        sortBy: 1, // 排序
        parentId: null, // 父id
        type: 'menu', // 类型
        hidden: false // 是否隐藏
      }
    },
    handleCreateSysPermission(type,parentId) {
      this.resetTemp()
      this.temp.type = type
      this.temp.parentId = parentId
      this.dialogStatus = 'create'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEditSysPermission(index, val) {
      this.temp = Object.assign({}, val)
      this.dialogStatus = 'update'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddSysPermission() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.type === 'menu') {
            this.temp.routerTitle = this.temp.authorityName;
            this.temp.authority = this.temp.routerName;
          }
          createSysPermission(this.temp).then(() => {
            // this.list.unshift(queryData)
            this.fetchListData()
            this.createDialogVisible = false
            this.$notify.success('权限创建成功!')
          })
        }
      })
    },
    handleUpdateSysPermission() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.temp.type === 'menu') {
            this.temp.routerTitle = this.temp.authorityName;
            this.temp.authority = this.temp.routerName;
          }
          updateSysPermission(this.temp).then(() => {
            this.reloadListData()
            this.createDialogVisible = false
            this.$notify.success('权限更新成功!')
          })
        }
      })
    },
    handleDeleteSysPermission(index, val) {
      const self = this
      this.$confirm('确定要删除该权限？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSysPermission(val.id).then(() => {
          self.reloadListData()
          self.$notify.success('权限已删除!')
        })
      }).catch(() => {})
    },
    handelChangeSortBy(oneId, oneSortBy, twoId, twoSortBy) {
      const sortChangeData = { oneId: oneId, oneSortBy: oneSortBy, twoId: twoId, twoSortBy: twoSortBy }
      changeSysPermissionSort(sortChangeData).then(res => {
        if (!res.code) {
          this.fetchListData()
        }
      })
    },
  }
}
</script>

